package com.ling.recipeassistant.ui.navigation

import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Favorite
import androidx.compose.material.icons.filled.Home
import androidx.compose.material.icons.filled.Person
import androidx.compose.material.icons.filled.Search
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.NavigationBar
import androidx.compose.material3.NavigationBarItem
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.navigation.NavDestination.Companion.hierarchy
import androidx.navigation.NavGraph.Companion.findStartDestination
import androidx.navigation.NavType
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.currentBackStackEntryAsState
import androidx.navigation.compose.rememberNavController
import androidx.navigation.navArgument
import com.ling.recipeassistant.R
import com.ling.recipeassistant.data.model.Recipe
import com.ling.recipeassistant.data.repository.RecipeRepository
import com.ling.recipeassistant.ui.screens.FavoritesScreen
import com.ling.recipeassistant.ui.screens.HomeScreen
import com.ling.recipeassistant.ui.screens.LoginScreen
import com.ling.recipeassistant.ui.screens.ProfileScreen
import com.ling.recipeassistant.ui.screens.RecipeDetailScreen
import com.ling.recipeassistant.ui.screens.SearchScreen
import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun RecipeAssistantApp() {
    val navController = rememberNavController()
    val navBackStackEntry by navController.currentBackStackEntryAsState()
    val currentRoute = navBackStackEntry?.destination?.route

    Scaffold(
        bottomBar = {
            // 只在非登录页显示底部导航栏
            if (currentRoute != Screen.Login.route) {
                NavigationBar {
                    val items = listOf(
                        NavigationItem(
                            route = Screen.Home.route,
                            title = stringResource(R.string.nav_home),
                            icon = Icons.Default.Home
                        ),
                        NavigationItem(
                            route = Screen.Search.route,
                            title = stringResource(R.string.nav_search),
                            icon = Icons.Default.Search
                        ),
                        NavigationItem(
                            route = Screen.Favorites.route,
                            title = stringResource(R.string.nav_favorites),
                            icon = Icons.Default.Favorite
                        ),
                        NavigationItem(
                            route = Screen.Profile.route,
                            title = stringResource(R.string.nav_profile),
                            icon = Icons.Default.Person
                        )
                    )

                    items.forEach { item ->
                        NavigationBarItem(
                            icon = { Icon(item.icon, contentDescription = item.title) },
                            label = { Text(item.title) },
                            selected = currentRoute == item.route,
                            onClick = {
                                navController.navigate(item.route) {
                                    popUpTo(navController.graph.findStartDestination().id) {
                                        saveState = true
                                    }
                                    launchSingleTop = true
                                    restoreState = true
                                }
                            }
                        )
                    }
                }
            }
        }
    ) { innerPadding ->
        NavHost(
            navController = navController,
            startDestination = Screen.Login.route,
            modifier = Modifier.padding(innerPadding)
        ) {
            composable(Screen.Home.route) {
                HomeScreen(
                    onRecipeClick = { recipe ->
                        navController.navigate(Screen.RecipeDetail.createRoute(recipe.id))
                    },
                    onCategoryClick = { category ->
                        // TODO: 导航到分类页面
                    }
                )
            }
            
            composable(Screen.Search.route) {
                SearchScreen(
                    onRecipeClick = { recipe ->
                        navController.navigate(Screen.RecipeDetail.createRoute(recipe.id))
                    }
                )
            }
            
            composable(Screen.Favorites.route) {
                FavoritesScreen(
                    onRecipeClick = { recipe ->
                        navController.navigate(Screen.RecipeDetail.createRoute(recipe.id))
                    }
                )
            }
            
            composable(Screen.Profile.route) {
                ProfileScreen(
                    onLogout = {
                        // 跳转到登录页并清空返回栈
                        navController.navigate(Screen.Login.route) {
                            popUpTo(0) { inclusive = true }
                        }
                    }
                )
            }
            
            // 菜谱详情页
            composable(
                route = Screen.RecipeDetail.route,
                arguments = listOf(
                    navArgument("recipeId") { type = NavType.StringType }
                )
            ) { backStackEntry ->
                val recipeId = backStackEntry.arguments?.getString("recipeId") ?: ""
                RecipeDetailScreenWrapper(
                    recipeId = recipeId,
                    onBackClick = { navController.popBackStack() },
                    onFavoriteClick = {
                        // TODO: 处理收藏逻辑
                    }
                )
            }
            
            composable(Screen.Login.route) {
                var isLoading by remember { mutableStateOf(false) }
                // 登录页面
                var error by remember { mutableStateOf<String?>(null) }
                LoginScreen(
                    onLogin = { username, password ->
                        isLoading = true
                        // TODO: 替换为实际登录逻辑
                        if (username == "user" && password == "123456") {
                            isLoading = false
                            error = null
                            // 登录成功，跳转主页
                            navController.navigate(Screen.Home.route) {
                                popUpTo(Screen.Login.route) { inclusive = true }
                            }
                        } else {
                            isLoading = false
                            error = "用户名或密码错误"
                        }
                    },
                    isLoading = isLoading,
                    error = error
                )
            }
        }
    }
}

@Composable
fun RecipeDetailScreenWrapper(
    recipeId: String,
    onBackClick: () -> Unit,
    onFavoriteClick: () -> Unit
) {
    // 这里应该从数据库获取菜谱详情
    // 为了演示，我们使用SampleData中的菜谱
    val recipe = com.ling.recipeassistant.data.local.SampleData.sampleRecipes.find { it.id == recipeId }
    
    recipe?.let {
        RecipeDetailScreen(
            recipe = it,
            onBackClick = onBackClick,
            onFavoriteClick = onFavoriteClick
        )
    }
}

sealed class Screen(val route: String) {
    object Home : Screen("home")
    object Search : Screen("search")
    object Favorites : Screen("favorites")
    object Profile : Screen("profile")
    object RecipeDetail : Screen("recipe_detail/{recipeId}") {
        fun createRoute(recipeId: String) = "recipe_detail/$recipeId"
    }
    object Login : Screen("login")
}

data class NavigationItem(
    val route: String,
    val title: String,
    val icon: androidx.compose.ui.graphics.vector.ImageVector
)